package com.browsesoft.htmlcomponent;

import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.w3c.dom.Element;

import com.browsesoft.ExtendElement;

public class ConnectedSelectComponent extends ReplacableParameterComponent {
	// 备份元素
	private Element element;

	// 保存request
	private HttpServletRequest request;

	public ConnectedSelectComponent(HTMLBasicComponent parent) throws Exception {
		super(parent);
	}

	/**
	 * @throws Exception
	 * 
	 */
	public void init(HttpServletRequest request, Element e) throws Exception {
		super.init(request, e);
		element = (Element) e.cloneNode(true);
	}

	/**
	 * 更新元素
	 * 
	 * @throws Exception
	 */
	public void updateElement() throws Exception {
		super.updateElement();
		Element e = this.getElement();
		this.setChildrenElement(e);
	}

	/**
	 * 设置要显示的子元素
	 */
	private void setChildrenElement(Element e) {
		// 根据元素属性中的parentName得到父选择框的值
		String parentName = e.getAttribute("parentname");
		String value = (String) request.getParameter(parentName);
		// 移除所有子元素
		ExtendElement.removeChilds(e);
		e.removeAttribute("defaultoptions");
		// 如果是新打开，默认显示第一个子
		if (value == null || value.equals("")) {
			Element first = (Element) ExtendElement.getElementByTagName(
					element, "parent").get(0);
			Element firstchild = (Element) first.cloneNode(true);
			e.appendChild(firstchild);
			return;
		}
		// 否则显示选择的子
		Iterator iter = ExtendElement.getElementByTagName(this.element,
				"parent").iterator();
		while (iter.hasNext()) {
			Element elem = (Element) iter.next();
			String attr = elem.getAttribute("value");
			if (attr.indexOf(value) != -1) {
				Element child = (Element) elem.cloneNode(true);
				e.appendChild(child);
			}
		}
	}

	/**
	 * @throws Exception
	 * 
	 */
	public void service(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		super.service(request, response);
		this.request = request;
	}
}
